package m.store.service;

import m.base.util.PowerUtil;
import m.common.model.util.ModelQueryList;
import m.common.model.util.ModelUpdate;
import m.common.model.util.ModelUpdateUtil;
import m.common.model.util.QueryCondition;
import m.common.service.Service;
import m.store.model.GoodsStockRecord;
import m.store.model.GuestInfo;
import m.store.model.StockInfo;
import m.store.model.StoreGoods;
import m.system.exception.MException;
import m.system.util.GenerateID;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class VirtualStockService extends Service {
    public void addVirtualStock(String guestOid, List<StoreGoods> goodsList) throws Exception {
        List<StockInfo> ls= ModelQueryList.getModelList(StockInfo.class,new String[]{"*"},null,
            QueryCondition.and(
                QueryCondition.eq("guest.oid",guestOid),
                QueryCondition.eq("type",StockInfo.Type_Virtual)
            )
        );
        StockInfo model;
        if(!ls.isEmpty()) {
            model=ls.get(0);
        }else{
            model=new StockInfo();
            model.setOid(GenerateID.generatePrimaryKey());
            model.setType(StockInfo.Type_Virtual);
            model.setGuest(new GuestInfo());
            model.getGuest().setOid(guestOid);
            model.setInputUser(PowerUtil.getSessionUser(true));
            model.setStore(PowerUtil.getSessionStore(true));
            ModelUpdateUtil.insertModel(model);
        }
        List<GoodsStockRecord> recordList=new ArrayList<>();
        for(StoreGoods goods : goodsList){
            GoodsStockRecord record=ModelQueryList.getModel(GoodsStockRecord.class,new String[]{"*"},
                QueryCondition.and(
                    QueryCondition.eq("goods.oid",goods.getOid()),
                    QueryCondition.eq("stock.oid",model.getOid())
                )
            );
            if(null==record) {
                record=new GoodsStockRecord();
                record.setOid(GenerateID.generatePrimaryKey());
                record.setStore(PowerUtil.getSessionStore(true));
                record.setStock(model);
                record.setOperDate(new Date());
                record.setGoods(goods);
                recordList.add(record);
            }
        }
        if(!recordList.isEmpty()) ModelUpdateUtil.insertModels(recordList.toArray(new GoodsStockRecord[0]));
    }
}
